import MapLocationPicker from '@/components/MapLocationPicker';
import { createCommunity } from '@/services/city-community';
import { EnvironmentOutlined } from '@ant-design/icons';
import { Button, Form, Input, InputNumber, Modal, message } from 'antd';
import { useState } from 'react';

const { TextArea } = Input;

interface CommunityCreateModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: (newCommunity?: any) => void;
  city: string;
}

const CommunityCreateModal: React.FC<CommunityCreateModalProps> = ({
  visible,
  onCancel,
  onSuccess,
  city,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [mapPickerVisible, setMapPickerVisible] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState<{
    lat: number;
    lng: number;
    address: string;
  } | null>(null);

  // 处理地图位置选择
  const handleLocationSelect = (location: {
    lat: number;
    lng: number;
    address: string;
  }) => {
    setSelectedLocation(location);
    console.log(location);
    // 自动填充表单中的经纬度和地址
    form.setFieldsValue({
      latitude: location.lat,
      longitude: location.lng,
      address: location.address,
    });
    setMapPickerVisible(false);
    message.success('位置选择成功');
  };

  // 保存小区信息
  const handleSave = async () => {
    try {
      const values = await form.validateFields();

      // 检查是否已选择位置
      if (!selectedLocation) {
        message.warning('请先选择小区位置');
        return;
      }

      setLoading(true);

      // 调用创建小区接口
      const result = await createCommunity({
        name: values.name,
        address: selectedLocation.address, // 使用地图选择的地址
        latitude: selectedLocation.lat, // 使用地图选择的纬度
        longitude: selectedLocation.lng, // 使用地图选择的经度
        description: values.description,
        city: city || values.city,
      });

      if (result.success) {
        message.success('小区创建成功');
        form.resetFields();
        setSelectedLocation(null);
        onSuccess(result.data);
      } else {
        message.error('小区创建失败');
      }
    } catch (error) {
      console.error('创建小区失败:', error);
      message.error('创建小区失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setSelectedLocation(null);
    onCancel();
  };

  return (
    <Modal
      title="创建新小区"
      open={visible}
      onOk={handleSave}
      onCancel={handleCancel}
      okText="创建"
      cancelText="取消"
      confirmLoading={loading}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          city: city,
        }}
      >
        <Form.Item
          label="城市"
          name="city"
          rules={[{ required: true, message: '请输入城市' }]}
        >
          <Input placeholder="请输入城市名称" disabled={!!city} />
        </Form.Item>

        <Form.Item
          label="小区名称"
          name="name"
          rules={[{ required: true, message: '请输入小区名称' }]}
        >
          <Input placeholder="请输入小区名称" />
        </Form.Item>

        <Form.Item
          label="详细地址"
          name="address"
          rules={[{ required: true, message: '请选择小区位置' }]}
        >
          <Input
            placeholder="请点击右侧按钮选择位置"
            suffix={
              <Button
                type="dashed"
                icon={<EnvironmentOutlined />}
                onClick={() => setMapPickerVisible(true)}
              >
                {selectedLocation ? '重新选择' : '选择位置'}
              </Button>
            }
          />
        </Form.Item>

        {/* 经纬度显示（只读） */}
        <Form.Item label="纬度" name="latitude">
          <InputNumber
            placeholder="请先选择位置"
            style={{ width: '100%' }}
            precision={6}
            readOnly
            disabled
          />
        </Form.Item>

        <Form.Item label="经度" name="longitude">
          <InputNumber
            placeholder="请先选择位置"
            style={{ width: '100%' }}
            precision={6}
            readOnly
            disabled
          />
        </Form.Item>

        <Form.Item label="小区描述" name="description">
          <TextArea
            rows={4}
            placeholder="请输入小区描述，例如：距离地铁站500米，周边配套齐全"
            maxLength={200}
            showCount
          />
        </Form.Item>
      </Form>

      {/* 地图位置选择器 */}
      <MapLocationPicker
        visible={mapPickerVisible}
        onCancel={() => setMapPickerVisible(false)}
        onConfirm={handleLocationSelect}
        apiKey="RMIBZ-6TTKK-S4LJ3-ATFPK-YNMBE-34BPQ"
        title="选择小区位置"
        width={900}
      />
    </Modal>
  );
};

export default CommunityCreateModal;
